(function(factory) {
    factory(Zepto);
}(function($) {
  var opts = null;
  var $slider;
  var $sliding;
  var speed = 2000;
  var duration = 400;
  var play = true;
  var cursor = false;
  var desc = false;
  var desc_position = "up";
  var shownum = false;
  var keys = "";
  var callback = null;
  var size = 0;
  var ms_width = 0;
  var ms_height = 0;
  var index = 1;
  var data;
  var timer;
  /**
   * 滑动插件（主要用于手机）
   * @method mdSlider
   * @param {object} options 参数对象  必选
   * 		@param {string} options.selector 必选   选择器唯一
   * 		@param {array} options.data 必选   图片信息  默认格式[{imgUrl:"", name: "", id: ""}, {imgUrl:"", name: "", id: ""}]
   * 		@param {object} options.keys 可选   配置data读取的key 默认格式{imgUrl:"imgUrl", name: "name", id: "id"}
   * 		@param {string} options.basePath 可选  拼接图片的头地址
   * 		@param {int} options.speed 可选  图片轮播速度  默认4000
   * 		@param {int} options.duration 可选  图片轮播过度时间  默认400
   * 		@param {boolean} options.play 可选  是否自动播放   true：自动播放， false：不自动播放  默认true
   * 		@param {boolean} options.cursor 可选  是否显示标记  true：显示， false：不显示  默认false
   * 		@param {boolean} options.desc 可选  是否显示图片信息  true：显示， false：不显示  默认false
   * 		@param {string} options.desc_position 可选  显示图片信息位置只接受“down”， 默认或其他附着在图片上, "down"显示在图片下方
   * 		@param {boolean} options.shownum 可选  是否总计图片数量  true：显示， false：不显示  默认false
   * 		@param {function} options.callback 可选  点击图片回掉函数  默认null
   * 
   *
   */
  function mdSlider(options) {
    var defaults = {
        "selector": null,
        "data": [],
        "keys": null,
        "basePath": null,
        "speed": 4000,
        "duration": 400,
        "play": true,
        "cursor": false,
        "desc": false,
        "desc_position": "",
        "shownum": false,
        "callback": null
    }
    opts = $.extend(defaults, options);
    selector = opts.selector;
    speed = opts.speed;
    duration = opts.duration;
    play = opts.play;
    cursor = opts.cursor;
    shownum = opts.shownum;
    desc = opts.desc;
    desc_position = opts.desc_position;
    keys = opts.keys || {};
    callback = opts.callback;
    $slider = $(selector);
    if($slider.length == 0) {
        return false;
    }
    ms_width = $slider.width();
    ms_height = $slider.height();
    data = opts.data;
    size = data.length;
    init();
  }
  
  function init() {
  	createHtml();
  	autoPlay();
  	bindEvents();
  }
  //创建html
  function createHtml() {
    var basePath = opts.basePath || "";
    var div = "";
    div += "<div class='md-slider'>";
    div += "<div class='md-sliding'>";
    for(var i = 0, len = data.length; i < len; i++ ) {
        var item = data[i];
        var img = item[keys.imgUrl] || item["imgUrl"];
        var name = item[keys.name] || item["name"];
        var id = item[keys.id] || item["id"];
        div += "<div class='ms-item' mi_id='"+id+"' style='width:"+ms_width+"px;background-image:url("+basePath+img+");' >";
        if(desc) {
        	div += "<div class='mi-desc'>"+name+"</div>";
    		div += "<div class='mi-desc-mask'></div>";
        }
        div += "</div>";
    }
    div += "</div></div>";
    $slider.html(div);
    $sliding = $slider.find(".md-sliding");
    if(desc && desc_position == "down") {
    	var m_h = parseInt($sliding.find(".mi-desc-mask").css("height"));
    	$sliding.height(ms_height - m_h);
    	$sliding.find(".mi-desc").css({"bottom": -m_h}).addClass("mi-desc-down");
    	$sliding.find(".mi-desc-mask").remove();
    } else {
    	$sliding.find(".mi-desc-mask").css("display", "block");
    }
    var size_ = size;
    if(size > 1) {
        var head = $sliding.find(".ms-item").eq(0).clone();
        var fail = $sliding.find(".ms-item").eq(size-1).clone();
        $sliding.prepend(fail).append(head).css({"left": -ms_width});
        size_ = size + 2;
    }
    $sliding.css({"display": "block"});
    $slider.find(".md-sliding").width((size_) * ms_width);
    if(cursor) {
    	var c_div = "<div class='ms-cursor'>"
    	for(var i = 1; i <= size; i++) {
    		if(i == 1) {
	    		c_div += "<span class='mc-cr active'>"+i+"</span>";
    		} else {
	    		c_div += "<span class='mc-cr'>"+i+"</span>";
    		}
    	}
    	c_div += "</div>";
    	$slider.find(".md-slider").append(c_div);
    }
    if(shownum) {
    	var num_div = "<div class='ms-num'><i>1</i><del>/</del><b>"+size+"</b></div>";
    	$slider.find(".md-slider").append(num_div);
    }
  }
  //滑动
  touchEvents(".md-sliding", function(type) {
  	if(size <= 1) {
    	return false;
    }
  	if(type == "left") {
  		index = index + 1;
  	}
  	if(type == "right") {
  		index = index - 1;
  	}
  	slidingAnimate();
  });
  //动画
  function slidingAnimate() {
  	$sliding.animate({left: -index * ms_width}, {duration: duration, easing: "ease-in-out", complete: function() {
  		if(index > size) {
  			$sliding.css("left", -ms_width);
  			index = 1;
  		}
  		if(index < 1) {
  			$sliding.css("left", -ms_width*(size));
  			index = size;
  		}
  		if(cursor) {
	  		$slider.find(".mc-cr").eq(index - 1).addClass("active").siblings().removeClass("active");
  		}
  		if(shownum) {
  			$slider.find(".ms-num i").text(index);
  		}
  	}});
  }
  //自动播放
  function autoPlay() {
    if(size <= 1) {
    	return false;
    }
  	timer = window.setInterval(function() {
	  	index++;
	  	slidingAnimate();
    }, speed);
  }
  //绑定回调事件
  function bindEvents() {
  	$slider.on("tap", ".ms-item", function() {
  		var id = $(this).attr("mi_id");
  		callback(id, $(this));
  	});
  }
  //滑动事件
  function touchEvents(selector, func) {
    var x1 = 0;
    var x2 = 0;
    $(document).on("touchstart", selector, function(e) {
        e.preventDefault();
        window.clearInterval(timer);
        if(e.originalEvent.targetTouches) {
	        x1 = e.originalEvent.targetTouches[0].pageX;
        } else {
        	x1 = e.pageX;
        }
    });
    $(document).on("touchend", selector, function(e) {
        e.preventDefault();
        if(e.originalEvent.changedTouches) {
	        x2 = e.originalEvent.changedTouches[0].pageX;
        } else {
        	x2 = e.pageX;
        }
        if((x1 - x2) < 0) {
            func("right");
        }
        if((x1 - x2) > 0) {
            func("left");
        }
        autoPlay();
    });
  }
  //注册到window
  $.extend(window, {"mdSlider": mdSlider});
}));
